//
//  RHDevReporSetVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/11/15.
//

#import "RHDevReporSetVC.h"
#import "ZYSwitch.h"
#import "RHReportConfigModel.h"
#import "KWTTimePickerView.h"
#import "RHChoiceTypeView.h"

@interface RHDevReporSetVC ()<QMUITextFieldDelegate>
@property (nonatomic, strong) QMUITextField *textField;

@property (nonatomic, strong) ZYSwitch *sw;

@property (nonatomic, strong) QMUILabel *receiveTimeLab;

@end

@implementation RHDevReporSetVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"报表推送设置".rh_localized;
   
    [self setupUI];
    [self reportConfigQurey];
}


-(void)clickWithIndex:(NSInteger)index
{
    kWeakSelf;
    if (index == 1) {
        KWTTimePickerView *pick = [[KWTTimePickerView alloc]initWithTitle:@"请选择".rh_localized deviceType:@"" CompleteBlock:^(NSString * _Nonnull time) {
            weakSelf.configModel.sendTime = time;
            weakSelf.receiveTimeLab.text = time;
        }];
        [pick setCurrentTime:self.configModel.sendTime];
        [pick show];
    }
    
}

#pragma mark ------ 报表配置
-(void)reportConfigQurey
{
    [QMUITips showLoadingInView:kAppWindow];
    [RHReportConfigModel startGetWithCompletionAPIKey:H_deviceReportConfigQuery argument:@{@"type":@(1)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            self.configModel = resultModel.data;
            if (self.configModel==nil) {
                self.configModel = [[RHReportConfigModel alloc]init];
            }
           
            self.receiveTimeLab.text = ValidNullDataToString(self.configModel.sendTime, @"--");
            self.textField.text = ValidNullDataToString(self.configModel.email, @"--");
            self.sw.on = [self.configModel.status integerValue];
        }else{
            self.configModel = [[RHReportConfigModel alloc]init];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        self.configModel = [[RHReportConfigModel alloc]init];
    }];
}

-(void)saveConfig
{
    if (![NSString isValidateEmail:self.configModel.email]) {
        [QMUITips showError:@"邮箱格式错误".rh_localized];
        return;
    }
    if (self.configModel.sendTime.length == 0) {
        [QMUITips showError:@"请选择接收时间".rh_localized];
        return;
    }
    NSDictionary *para = @{
        @"email":self.configModel.email,
        @"status":@([self.configModel.status integerValue]),
        @"sendTime":self.configModel.sendTime,
      
        @"timeZone":[NSTimeZone localTimeZone].name,
        @"type":@(1)
    };
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startWithCompletionAPIKey:H_deviceReportConfigSave argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"设置成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.saveBlock) {
                    self.saveBlock();
                }
                [self.navigationController popViewControllerAnimated:YES];
                
            });
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
}



-(void)setupUI{
    kWeakSelf;
 
    UIView *bgView =  [[UIView alloc] initWithFrame:CGRectMake(15, 10, SCREEN_WIDTH-30,105)];
    [bgView setBackgroundColor:UIColor.whiteColor];
    [bgView rounded:8 width:1 color:kBorderColor];
    
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(15);
    }];
    
    __block UIView *lastView;
    //根据要显示的信息创建label
    NSArray* titles = @[@"接收邮箱".rh_localized,@"接收时间".rh_localized,@"开启推送".rh_localized];
    [titles enumerateObjectsUsingBlock:^(NSString*  _Nonnull title, NSUInteger idx, BOOL * _Nonnull stop) {
       
        UIView *itemView = [self itemViewWithTitle:title index:idx];
        [bgView addSubview:itemView];
        if (lastView) {
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_offset(0);
                make.top.equalTo(lastView.mas_bottom);
                make.height.equalTo(lastView);
            }];
        }else{
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_offset(0);
                make.top.mas_offset(5);
                make.height.offset(50);
            }];
        }
        lastView = itemView;
        //线条
        if (idx != titles.count-1) {
            UIView *line = kView;
            line.backgroundColor = kCOLOR_HEX(@"#EBEDF0");
            [itemView addSubview:line];
            [line mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(15);
                make.right.mas_offset(-15);
                make.height.offset(1);
                make.bottom.mas_offset(0);
            }];
        }
    }];
    [lastView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-5);
    }];
    
    
    QMUIButton *createBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [createBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [createBtn setTitle:@"确认".rh_localized forState:UIControlStateNormal];
    [createBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [createBtn.layer setCornerRadius:8];
    [createBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:createBtn];
    [createBtn addTarget:self action:@selector(saveConfig) forControlEvents:UIControlEventTouchUpInside];
    [createBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
}


-(UIView*)itemViewWithTitle:(NSString *)title index:(NSInteger)index
{
    kWeakSelf;
    
    
    UIView *itemView = kView;
    QMUILabel *titleLab = [[QMUILabel alloc]init];
    [itemView addSubview:titleLab];
    titleLab.text = [NSString stringWithFormat:@"%@:",title.rh_localized];
    titleLab.textColor = [UIColor colorWithHexString:@"3F4443" alpha:0.8];
    titleLab.font = kSYSTEMFONT(14);
    titleLab.tag = 100+index;
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.numberOfLines = 2;
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
        make.width.offset(100);
    }];
    
    
    UIImageView *arrow = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow"]];
    [itemView addSubview:arrow];
    [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_offset(0);
        make.right.mas_offset(-15);
        make.width.height.offset(18);
    }];
    
    QMUILabel *contentLab = [[QMUILabel alloc]init];
    [itemView addSubview:contentLab];
    contentLab.text = @"--";
    contentLab.textColor = [UIColor colorWithHexString:@"3F4443" alpha:0.8];
    contentLab.font = kSYSTEMFONT(14);
    contentLab.tag = 200+index;
    contentLab.textAlignment = NSTextAlignmentRight;
    contentLab.numberOfLines = 2;
    contentLab.adjustsFontSizeToFitWidth = YES;
    contentLab.minimumScaleFactor = 0.8;
    [contentLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLab.mas_right).offset(5);
        make.right.equalTo(arrow.mas_left).offset(-3);
        make.centerY.mas_offset(0);
    }];
    
    if (index == 0) {
        arrow.hidden = YES;
        contentLab.hidden = YES;
        _textField = [[QMUITextField alloc]init];
        _textField.textAlignment = NSTextAlignmentRight;
        _textField.font = kSYSTEMFONT(14);
        _textField.textColor = kCOLOR_HEX(@"#171A1D");
        _textField.text = self.configModel.email;
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.delegate = self;
        [itemView addSubview:_textField];
        [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(titleLab.mas_right).offset(10);
            make.right.equalTo(arrow.mas_left).offset(-3);
            make.centerY.mas_offset(0);
        }];
        
        [[_textField rac_textSignal]subscribeNext:^(NSString * _Nullable text) {
            weakSelf.configModel.email = text;
        }];
    }
    
    if (index == 1) {
        self.receiveTimeLab = contentLab;
        self.receiveTimeLab.text = self.configModel.sendTime;
    }
    
    
    if (index == 2) {
        arrow.hidden = YES;
        contentLab.hidden = YES;
        _sw = [[ZYSwitch alloc]initWithFrame:CGRectMake(0, 0, 44, 25)];
        _sw.onTintColor = CMainColorGreen;
        _sw.on = [self.configModel.status boolValue];
        [itemView addSubview:_sw];
        [_sw mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_offset(-15);
            make.centerY.mas_offset(0);
            make.width.offset(44);
            make.height.offset(25);
        }];
        [[_sw rac_signalForControlEvents:UIControlEventValueChanged]subscribeNext:^(__kindof ZYSwitch * _Nullable x) {
            weakSelf.configModel.status = [NSString stringWithFormat:@"%ld",x.isOn];
        }];
    }
    
    
    
    if (index == 1) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
        [tap.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            [weakSelf clickWithIndex:index];
        }];

        [itemView addGestureRecognizer:tap];
    }
   
    

    
    return itemView;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if([textField.text isEqualToString:@"--"])  {
        textField.text = @"";
    }
}

@end
